<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="C++," />










<meta name="description" content="C++ 常用关键字介绍">
<meta name="keywords" content="C++">
<meta property="og:type" content="article">
<meta property="og:title" content="C++ 关键字整理">
<meta property="og:url" content="https://zhaoyongcnsx.github.io/2018/10/05/C++ 关键字整理/index.html">
<meta property="og:site_name" content="zhaoyongCNSX Blogs">
<meta property="og:description" content="C++ 常用关键字介绍">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-10-05T08:33:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="C++ 关键字整理">
<meta name="twitter:description" content="C++ 常用关键字介绍">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zhaoyongcnsx.github.io/2018/10/05/C++ 关键字整理/"/>





  <title>C++ 关键字整理 | zhaoyongCNSX Blogs</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhaoyongCNSX Blogs</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zhaoyongcnsx.github.io/2018/10/05/C++ 关键字整理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaoyongCNSX">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/myLogo.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhaoyongCNSX Blogs">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">C++ 关键字整理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-05T16:33:10+08:00">
                2018-10-05
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-10-05T16:33:10+08:00">
                2018-10-05
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/programming/" itemprop="url" rel="index">
                    <span itemprop="name">编程</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/programming/C/" itemprop="url" rel="index">
                    <span itemprop="name">C++</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/10/05/C++ 关键字整理/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2018/10/05/C++ 关键字整理/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/10/05/C++ 关键字整理/" class="leancloud_visitors" data-flag-title="C++ 关键字整理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.3k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  20
                </span>
              
            </div>
          

          
              <div class="post-description">
                  C++ 常用关键字介绍
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>友情提示: 你可以选择以下镜像网站进行阅读:</p>
<ul>
<li><a href="https://zhaoyongcnsx.github.io">GitHub Pages</a></li>
<li><a href="http://47.92.146.3" target="_blank" rel="noopener">国内个人站</a></li>
</ul>
</blockquote>
<h1 id="1-auto"><a href="#1-auto" class="headerlink" title="1. auto"></a>1. auto</h1><p>C++11 引入的新的<strong>类型说明符</strong>. 与具体的 int,double 之类的类型说明符不同，其作用为：让编译器通过<strong>初始值</strong>来推算变量类型。因此 auto 变量必须要有初始值。</p>
<p>可使用 auto 在一条声明语句中声明多个变量。<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//a 为 int 类型变量，b 为 int*变量</span></span><br><span class="line"><span class="keyword">auto</span> a=<span class="number">1</span>, *b=&amp;a;</span><br></pre></td></tr></table></figure></p>
<p>当以下情况时，auto 推断出的类型与初始值类型并不完全一致：</p>
<ul>
<li>初始值为<strong>引用</strong>类型时，将直接使用所引用对象的类型作为 auto 类型。</li>
<li>auto 一般会忽略<strong>顶层 const</strong>, 保留<strong>底层 const</strong>. 若想让 auto 类型为一个顶层 const, 需使用<code>const auto</code>.</li>
<li>auto 与 &amp; 引用一起使用，将引用类型设置为 auto.</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a;</span><br><span class="line"><span class="keyword">auto</span> &amp;b = a;    <span class="comment">//b 为 int 引用</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">auto</span> &amp;c = <span class="number">20</span>;    <span class="comment">//c 为整形常量引用。可绑定字面值</span></span><br></pre></td></tr></table></figure>
<h1 id="2-const"><a href="#2-const" class="headerlink" title="2. const"></a>2. const</h1><ul>
<li>修饰函数</li>
<li>修饰<strong>指针 / 引用</strong>类型的变量</li>
<li>常对象成员</li>
<li><code>mutable</code> 为其反义词</li>
</ul>
<h2 id="2-1-修饰函数"><a href="#2-1-修饰函数" class="headerlink" title="2.1. 修饰函数"></a>2.1. 修饰函数</h2><ul>
<li>修饰成员函数整体<ul>
<li>释义：修饰成员函数，也就是修饰其中的<code>this</code>指针，使其无法修改类中的数据。</li>
<li>注意：在常成员函数中，禁止对类属性进行<strong>修改</strong>, 也禁止调用本类的<em>非常成员函数</em>.</li>
<li>使用：任何不修改类属性的方法，均应该被声明为常成员函数。</li>
</ul>
</li>
<li>修饰函数形参<ul>
<li>释义：说明本形参在该函数中不可被修改。一般和引用一起使用。（使用引用减少数据拷贝的消耗，又需要防止其被<em>无意修改</em>).</li>
<li>使用：在该形参不需要被修改时，尽量用 const 修饰。</li>
</ul>
</li>
<li><p>修饰返回的指针或引用</p>
<ul>
<li>释义：表示返回值不可被修改。只能把该指针赋给用 const 修饰的指针变量或引用。</li>
<li>注意：当函数返回的为值时，在接受返回值的过程中，会进行值传递。所以当返回类型为值时，使用 const 修饰无效。</li>
<li><p>返回引用的情况不多，有以下两个用途</p>
<ul>
<li><p>类重载赋值运算符时，方便实现赋值的链式表达。</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClass</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="comment">// 构造，析构，拷贝构造 都省略了</span></span><br><span class="line">    frind <span class="keyword">const</span> ostream&amp; <span class="keyword">operator</span>=(ostream&amp;out, MyClass val) &#123;</span><br><span class="line">        out &lt;&lt; val.m_num;</span><br><span class="line">        <span class="keyword">return</span> out;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="keyword">int</span> m_num;</span><br><span class="line">&#125;;</span><br><span class="line">MyClass a, b, c;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; a &lt;&lt; b &lt;&lt; c;</span><br></pre></td></tr></table></figure>
</li>
<li><p>用于返回临时变量时，防止外部对该临时变量进行修改。</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="2-2-修饰-指针-引用-类型的变量"><a href="#2-2-修饰-指针-引用-类型的变量" class="headerlink" title="2.2. 修饰 指针 引用 类型的变量"></a>2.2. 修饰 指针 引用 类型的变量</h2><ul>
<li>顶层 const<ul>
<li>只可用于修饰指针。修饰引用时，无意义。（因为引用本来就不可改变指向的位置)</li>
<li>格式：<code>类型 *const 变量名</code> eg: <code>int *const num</code></li>
<li>释义：<strong>常量指针</strong>, const 用于修饰该变量，使其值不可改变。（指针值不变，也就是说指针所指位置不可变)</li>
<li>特别说明：<strong>常量指针</strong>和<strong>常量引用</strong>.<ul>
<li>其中常量引用说明的是：<em>可指向常量的引用</em>. 且常量引用为底层 const.</li>
</ul>
</li>
</ul>
</li>
<li>底层 const<ul>
<li><code>const 类型 &amp; 变量名</code> eg: <code>const int &amp;a</code><ul>
<li>可指向常量的引用。不论是常量还是变量，都无法通过该引用来修改其值。</li>
<li>常量需要使用引用时，必须使用该语法指定引用。</li>
<li><code>const 类型 * 变量名</code> eg: <code>const int *a</code>. 可指向常量的指针。（意义同上)</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="2-3-常对象成员"><a href="#2-3-常对象成员" class="headerlink" title="2.3. 常对象成员"></a>2.3. 常对象成员</h2><ul>
<li>用于修饰类的数据成员</li>
<li><p>初始化的方法</p>
<ul>
<li><p>使用初始化列表。在类的构造函数中使用</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClass</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">MyClass(): num(<span class="number">10</span>), str(<span class="string">"abc"</span>) &#123;</span><br><span class="line"><span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> num;</span><br><span class="line"><span class="keyword">const</span> String str;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
<li><p>用作静态成员变量（类变量). 因为其是独立进行初始化的。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClass</span> &#123;</span></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">int</span> num;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 尽量在。cpp 中进行类变量的定义</span></span><br><span class="line"><span class="comment">// 若只是类变量定义，可不进行赋值。但此处还有 const 修饰，必须进行赋值，否则默认赋值。</span></span><br><span class="line"><span class="keyword">int</span> MyClass::num = <span class="number">10</span>;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<h1 id="3-constexpr"><a href="#3-constexpr" class="headerlink" title="3. constexpr"></a>3. constexpr</h1><ul>
<li>定义：常量表达式（const expression)：值不会改变，且在编译中就得到计算结果的表达式。</li>
<li><p>定义中有两个关键点：</p>
<ul>
<li>值不会改变，也就必须为<code>const</code>类型。</li>
<li><p>在编译中就要得到计算结果。一个对象 / 表达式是否为常量表达式，由其<strong>数据类型</strong>和<strong>初始值</strong>共同决定。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a = <span class="number">10</span>;    <span class="comment">// 非常量表达式（非 const)</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> d = func();    <span class="comment">// 非常量表达式 （无法在编译中得到计算结果）</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> b= <span class="number">10</span>;    <span class="comment">// 常量表达式</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> c = b+<span class="number">1</span>;    <span class="comment">// 常量表达式</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<ul>
<li>constexpr 并不是类型说明符，虽然与类型说明符 const 一样，均可放于类型说明符前面或后面，但一般将其放于前面。</li>
</ul>
<h2 id="3-1-constexpr变量"><a href="#3-1-constexpr变量" class="headerlink" title="3.1. constexpr变量"></a>3.1. <code>constexpr</code>变量</h2><p>constexpr 比 const 更为严格。constexpr 变量是必须由常量表达式初始化的 const 变量。</p>
<p>在复杂系统中，几乎不可能分辨一个初始值到底是不是常量表达式。所以 C++11 规定：可将变量声明为<code>constexpr</code>类型变量，以便由编译器验证变量值是否为一个常量表达式。该变量一定是一个<strong>常量</strong>， 且必须使用常量表达式初始化。</p>
<p>若某变量是一个常量表达式，则把它声明为<code>constexpr</code>类型</p>
<h3 id="3-1-1-字面值类型"><a href="#3-1-1-字面值类型" class="headerlink" title="3.1.1. 字面值类型"></a>3.1.1. 字面值类型</h3><p>字面值类型（literal type），声明<code>constexpr</code>变量时可用的类型。因为需在编译时得到计算，说以字面值类型一般比较简单。</p>
<p>字面值类型包含：</p>
<ul>
<li>算数类型</li>
<li>引用和指针。但初始值被严格限制。指针初始值必须为 nullptr，0，存储于某固定地址中的对象（全局变量，静态局部变量，堆空间中的变量）。</li>
<li>。</li>
</ul>
<h2 id="3-2-constexpr和指针"><a href="#3-2-constexpr和指针" class="headerlink" title="3.2. constexpr和指针"></a>3.2. <code>constexpr</code>和指针</h2><p>作用与顶层 const 类似，修饰的为指针本身。</p>
<h2 id="3-3-constexpr函数"><a href="#3-3-constexpr函数" class="headerlink" title="3.3. constexpr函数"></a>3.3. <code>constexpr</code>函数</h2><p>能作为<code>constexpr</code>变量的初始值的函数。在给 constexpr 变量初始化时，编译器将函数调用替换为其结果值。且为了能在编译过程中展开，其被隐式指定为<strong>内联函数</strong>。<br>该函数需满足以下条件：</p>
<ul>
<li>函数返回类型及所有形参类型都必须为<strong>字面值类型</strong>。</li>
<li>函数体中必须有且只有一条 return 语句。</li>
</ul>
<p>该函数不一定返回常量表达式。<br>通常把 constexpr 函数放于头文件，因为它们允许在程序中被多次定义（每次定义必须相同），且编译器要将函数展开为内联形式，除了需要函数声明，还需要函数的实现。</p>
<hr>
<h1 id="4-decltype"><a href="#4-decltype" class="headerlink" title="4. decltype"></a>4. decltype</h1><p>C++11 引入的第二种<strong>类型说明符</strong>. 用于分析并返回操作数的数据类型。</p>
<ul>
<li>与<code>auto</code>不同点：<br>只分析表达式，并得到其类型。并不实际进行运算（只进行类型之间的计算)</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">decltype</span>(a+b) c;    <span class="comment">//c 类型为 a+b 计算结果的类型。但 a+b 并未进行真正计算。</span></span><br></pre></td></tr></table></figure>
<h1 id="5-default"><a href="#5-default" class="headerlink" title="5. default"></a>5. default</h1><blockquote>
<p>C++11 特性</p>
</blockquote>
<ul>
<li>背景：C++ 类中有 4 个特殊的成员函数：默认构造，析构，默认拷贝构造，默认 = 重载。若编写时未显式定义，则编译器会生成默认的函数。且编译器生成的要比我们写的 {} 函数体为空的函数要执行效率高。</li>
<li>问题：以，默认构造函数为例：但当我们编写了自己的构造函数，… 时，默认构造函数就不会生成。为了要调用默认构造函数，必须自己将其写出。eg: A() {} 但这样又累，执行效率也不如编译器自动生成的高。所以 defaulted 函数粉墨登场。</li>
<li>语法：以默认构造为例：A() =default; 这样写后，编译器就会自动为其生成函数体了。保留了之前的执行效率。</li>
<li>当与虚函数结合使用时，以析构函数为例：virtual ~A() =default; 这样当子类继承该类时，就可以实现子类析构时的多态。</li>
<li>defaulted 函数即可在类内定义 (inline) 也可在类外定义 (out-of-line).</li>
<li>只可用于以上四种特殊的成员函数上。</li>
<li><p>代码示例</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">X</span>&#123;</span></span><br><span class="line">   <span class="keyword">public</span>:</span><br><span class="line">       X() = <span class="keyword">default</span>; <span class="comment">// 默认构造函数</span></span><br><span class="line">       X(<span class="keyword">const</span> X&amp;);</span><br><span class="line">       X&amp; <span class="keyword">operator</span> = (<span class="keyword">const</span> X&amp;);</span><br><span class="line">       <span class="keyword">virtual</span> ~X() = <span class="keyword">default</span>;  <span class="comment">// 析构函数 + 虚函数</span></span><br><span class="line">&#125;;</span><br><span class="line">X::X(<span class="keyword">const</span> X&amp;) = <span class="keyword">default</span>;  <span class="comment">// 拷贝构造函数</span></span><br><span class="line">X&amp; X::<span class="keyword">operator</span> = (<span class="keyword">const</span> X&amp;) = <span class="keyword">default</span>;     <span class="comment">// 拷贝赋值操作符</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="6-delete"><a href="#6-delete" class="headerlink" title="6. delete"></a>6. delete</h1><p>释放 new 所分配的对象。</p>
<ul>
<li><p>释放一个变量空间</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">delete</span> p;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li><p>释放 new 分配的数组，用<code>delete []</code>, 且<code>[]</code>中无需写出长度</p>
<figure class="highlight smali"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">delete []<span class="built_in"> array </span>;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ol>
<li>背景：因为当我们没有显式的定义赋值构造，拷贝构造函数。.., 当需要时，编译器会自动帮我们生成。（很便利是吧？但也太无脑了。) 当我们不想让对象之间相互拷贝呢？我能就需要阻止编译器的这种行为。</li>
<li>deleted 函数，用于禁用掉想禁用的函数。（任何函数都行). 禁用某些不期望的转换或操作符。</li>
<li>语法：eg: A(const A &amp;)=delete;</li>
<li>只能在函数中定义。</li>
</ol>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 在 Qt 中，常用于构建 单例 类中。（禁用掉拷贝构造和 = 重载。)</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">X</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">  X(<span class="keyword">double</span>);                  <span class="comment">// 可以 X a(1)</span></span><br><span class="line">  X(<span class="keyword">int</span>) = <span class="keyword">delete</span>;            <span class="comment">// 不可以 X a(1.2)</span></span><br><span class="line">  <span class="function"><span class="keyword">void</span> *<span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span>)</span> </span>= <span class="keyword">delete</span>;     <span class="comment">// 不能用 new X</span></span><br><span class="line">  <span class="keyword">void</span> *<span class="keyword">operator</span> <span class="keyword">new</span>[](<span class="keyword">size_t</span>) = <span class="keyword">delete</span>;     <span class="comment">// 不能用 new X[]</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h1 id="7-explicit"><a href="#7-explicit" class="headerlink" title="7. explicit"></a>7. explicit</h1><p>修饰构造函数，作用为：可以禁止”单参数构造函数”被用于自动类型转换中。</p>
<blockquote>
<p>详见 类。md 中的”显式构造函数”部分。</p>
</blockquote>
<h1 id="8-extern-链接指示"><a href="#8-extern-链接指示" class="headerlink" title="8. extern 链接指示"></a>8. <code>extern</code> 链接指示</h1><ul>
<li>C++ 使用链接指示 (<em>linkage directive</em>) 指出任意非 C++ 函数所用语言。</li>
<li>链接指示不能出现在<em>类定义</em>或<em>函数定义</em>内部。且必须<strong>在函数的每个声明中都出现</strong>.</li>
<li><p><code>extern &quot;C&quot;</code>: 告知编译器在编译这个符号（函数或变量) 时，按照 C 的规则对符号进行处理。(C++ 因为有函数重载等，所以在符号翻译时，会增加很多额外的东西，但 C 翻译时就会简单许多。)</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 单语句链接指示</span></span><br><span class="line"><span class="keyword">extern</span> <span class="string">"C"</span> <span class="function"><span class="keyword">int</span> <span class="title">a</span><span class="params">(<span class="keyword">void</span>)</span></span>;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 复合语句链接指示</span></span><br><span class="line"><span class="keyword">extern</span> <span class="string">"C"</span> &#123;</span><br><span class="line">    <span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"c_inc.h"</span></span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">b</span><span class="params">(<span class="keyword">void</span>)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li><p>编译器在编译 C++ 版本的程序时，会定义<code>__cplusplus</code>变量。所以可以使用该变量进行如下处理：</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> __cplusplus</span></span><br><span class="line"><span class="keyword">extern</span> <span class="string">"C"</span> &#123;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line"> </span><br><span class="line"><span class="comment">//includ c 头文件</span></span><br><span class="line"><span class="comment">//---- 代码区 ---</span></span><br><span class="line"> </span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> __cplusplus</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li><p>指向 extern “C” 的函数指针：如果一个函数指针要指向一个 C 函数，则这个函数指针声明时，也需要使用相同的链接指示。</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">extern</span> <span class="string">"C"</span> <span class="function"><span class="keyword">void</span> <span class="title">funcA</span><span class="params">(<span class="keyword">int</span>)</span></span>;    <span class="comment">// C 函数</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">funcB</span><span class="params">(<span class="keyword">int</span>)</span></span>;            <span class="comment">//c++ 函数</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">extern</span> <span class="string">"C"</span> <span class="keyword">void</span> (*pf1)(<span class="keyword">int</span>);</span><br><span class="line"><span class="keyword">void</span> (*pf2)(<span class="keyword">int</span>);</span><br><span class="line"> </span><br><span class="line">pf1 = funcA;    <span class="comment">// 正确</span></span><br><span class="line">pf1 = funcB;    <span class="comment">// 错误。不匹配</span></span><br><span class="line"> </span><br><span class="line">pf2 = funcA;    <span class="comment">// 错误。不匹配</span></span><br><span class="line">pf2 = funcB;    <span class="comment">// 正确。</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>链接指示对整个声明都有效。不仅对函数有效，还对类型为<em>函数指针</em> 的<em>返回值</em> 或<em>形参类型</em> 有效。所以如果想让函数与形参和返回值的链接指示不同，可使用<em>类型别名</em>.</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// f1 是一个 C 函数，形参也是一个 C 函数</span></span><br><span class="line">extern "C" void f1(void(*)(int));</span><br><span class="line"> </span><br><span class="line"><span class="comment">// PF_cfunc 类型为一个指向 C 函数 的函数指针。</span></span><br><span class="line"><span class="keyword">extern</span> <span class="string">"C"</span> <span class="function"><span class="keyword">typedef</span> <span class="title">void</span> <span class="params">(*PF_cfunc)</span><span class="params">(<span class="keyword">int</span>)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(PF_cfunc)</span></span>;    <span class="comment">//f2 为 C++ 函数，参数为一个指向 C 函数的函数指针</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="9-friend"><a href="#9-friend" class="headerlink" title="9. friend"></a>9. friend</h1><ul>
<li>友元关系只是<strong>单向</strong>的，不可传递与继承。</li>
<li>友元关系在一定程度上，打破了封装的原则，所以不可滥用！</li>
<li>友元关系可分为<ul>
<li>友元函数</li>
<li>友元类</li>
</ul>
</li>
</ul>
<h2 id="9-1-友元函数"><a href="#9-1-友元函数" class="headerlink" title="9.1. 友元函数"></a>9.1. 友元函数</h2><ul>
<li>作用：设置一个非该类成员的函数为该类的友元函数，该函数可访问该类的私有成员。</li>
<li><p>使用场景：</p>
<ul>
<li>综述：无法实现为成员函数，但还需要访问私有成员时。</li>
<li><p>运算符重载</p>
<ul>
<li><p>当第一个参数非本类类型时，无法实现其为本类的成员函数。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClass</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="comment">// 构造函数，析构函数，拷贝构造函数 省略</span></span><br><span class="line"> </span><br><span class="line">    <span class="comment">// 可实现为成员函数，也可实现为 友元函数。此处实现为成员函数</span></span><br><span class="line">    MyClass <span class="keyword">operator</span>+(<span class="keyword">const</span> MyClass a) &#123;</span><br><span class="line">        <span class="keyword">return</span> MyClass(x+a.x, y+a.y);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 因为第一个参数非本类类型，只可实现为友元函数</span></span><br><span class="line">    <span class="keyword">friend</span> ostream &amp;<span class="keyword">operator</span>&lt;&lt;(ostream &amp;out, <span class="keyword">const</span> MyClass num);</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="keyword">double</span> x, y;</span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line">ostream &amp; <span class="keyword">operator</span>&lt;&lt;(ostream &amp;out, <span class="keyword">const</span> MyClass num)</span><br><span class="line">&#123;</span><br><span class="line">    out &lt;&lt; num.x &lt;&lt; num.y &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="keyword">return</span> out;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>一些特殊情况，为提高执行效率，直接操作私有成员，而非通过其封装好的接口操作。</p>
</li>
</ul>
</li>
</ul>
<h2 id="9-2-友元类"><a href="#9-2-友元类" class="headerlink" title="9.2. 友元类"></a>9.2. 友元类</h2><ul>
<li>作用：使一个类可以访问目标类的任意成员（包括私有成员).</li>
<li>方法：类 A 要访问类 B 的私有成员，则在类 B 的定义中添加<code>friend class A;</code>.</li>
<li><p>示例：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> &#123;</span></span><br><span class="line">    <span class="comment">// 省略 构造函数，析构函数，拷贝构造函数</span></span><br><span class="line"> </span><br><span class="line">    <span class="keyword">friend</span> <span class="class"><span class="keyword">class</span> <span class="title">A</span>;</span></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="keyword">int</span> m_x, m_y;</span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    A() &#123;</span><br><span class="line">        B b;</span><br><span class="line">        <span class="comment">// 直接访问 B 的私有成员</span></span><br><span class="line">        <span class="built_in">cout</span> &lt;&lt; b.m_x &lt;&lt; b.m_y &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="10-inline"><a href="#10-inline" class="headerlink" title="10. inline"></a>10. inline</h1><p>用于：</p>
<ul>
<li>内联函数</li>
<li>成员函数的内联写法</li>
</ul>
<h1 id="11-mutable"><a href="#11-mutable" class="headerlink" title="11. mutable"></a>11. mutable</h1><ul>
<li><code>mutable</code>为<em>可变的，易变的</em> 的含义。与<em>constant</em> (const) 相对。</li>
<li>用于突破<code>const</code>对于成员函数的限制。<code>const</code>修饰的<strong>成员函数</strong>可修改<code>mutable</code>修饰的<strong>成员变量</strong>.</li>
<li><p>示例：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">func1</span><span class="params">()</span><span class="keyword">const</span> </span>&#123;</span><br><span class="line">        count++;    <span class="comment">// 可修改经过 mutable 修饰的成员变量</span></span><br><span class="line">        <span class="comment">// 不可修改其他成员变量，eg: num</span></span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="keyword">mutable</span> <span class="keyword">int</span> count;</span><br><span class="line">    <span class="keyword">int</span> num;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="12-new"><a href="#12-new" class="headerlink" title="12. new"></a>12. new</h1><p>动态分配内存到堆上，可运行时指定储存区大小</p>
<ul>
<li><p>分配一个变量</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">RN *p = <span class="keyword">new</span> RN(<span class="number">3</span>, <span class="number">4</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>分配多个</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">RN *<span class="built_in">array</span> = <span class="keyword">new</span> RN『个数』;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="13-operator"><a href="#13-operator" class="headerlink" title="13. operator"></a>13. operator</h1><p>运算符重载</p>
<ul>
<li>C++ 将运算符等同于函数看待</li>
<li>运算符重载的类型<ul>
<li>左操作数的成员函数：eg: 赋值号<code>=</code>只可被重载为成员函数</li>
<li>一般函数</li>
</ul>
</li>
</ul>
<h1 id="14-static"><a href="#14-static" class="headerlink" title="14. static"></a>14. static</h1><ul>
<li>静态成员变量：（在 Python 中叫做类变量), 为该类所有，而非某一个具体实例。<ul>
<li>在类内声明。但必须在类外进行初始化。因为在初始化时，才会开辟内存空间 (data 段)（类定义，实例化时都不会给静态成员变量开辟空间). 初始化时可以不赋值，则系统自动赋默认值。（全局为 0, 局部为垃圾值)</li>
<li>静态成员变量的使用：通过 类名 或 任意实例名 调用。可以在成员函数中使用。</li>
</ul>
</li>
<li>静态成员函数：与普通成员函数相比，无 this 指针。所以只能访问该类中的静态成员变量。</li>
<li>特别注意：成员函数，或普通函数中使用 static 变量。其作用为扩大了生命周期，但访问范围未改变。<ul>
<li>因为成员函数其实是不属于每个实例的，所以其中的 static 变量和在普通函数中使用一样，都是<strong>共用</strong>的。</li>
</ul>
</li>
</ul>
<h2 id="14-1-示例"><a href="#14-1-示例" class="headerlink" title="14.1. 示例"></a>14.1. 示例</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>&#123;</span></span><br><span class="line"><span class="keyword">static</span> myTypeInt a;</span><br><span class="line"><span class="keyword">static</span> myTypeP *b;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">myFunc</span><span class="params">()</span></span>;        <span class="comment">// 静态成员函数，只能访问 a 和 *b</span></span><br><span class="line"> </span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line">在 .cpp 中进行初始化静态成员变量，（在此时开辟空间):</span><br><span class="line">myTypeInt a;    <span class="comment">// 可以不赋值</span></span><br><span class="line">myTypeP *b = NUll;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>成员函数中使用 static 变量。<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    Test(<span class="built_in">std</span>::<span class="built_in">string</span> str) &#123;</span><br><span class="line">        m_str = str;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Func</span><span class="params">(<span class="keyword">void</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">int</span> s_num = <span class="number">1</span>;    <span class="comment">// 每个实例都共用该变量。</span></span><br><span class="line">        s_num++;</span><br><span class="line">        <span class="built_in">cout</span> &lt;&lt; <span class="string">"Str: "</span> &lt;&lt; m_str.c_str() &lt;&lt; <span class="string">"  NUM: "</span> &lt;&lt; s_num &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">string</span> m_str;</span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="function">Test <span class="title">T1</span><span class="params">(<span class="string">"T1"</span>)</span></span>;</span><br><span class="line">    <span class="function">Test <span class="title">T2</span><span class="params">(<span class="string">"T2"</span>)</span></span>;</span><br><span class="line"> </span><br><span class="line">    T1.Func();    <span class="comment">// "Str: T1  NUM: 2"</span></span><br><span class="line">    T1.Func();    <span class="comment">// "Str: T1  NUM: 3"</span></span><br><span class="line">    T2.Func();    <span class="comment">// "Str: T2  NUM: 4"</span></span><br><span class="line"> </span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
</blockquote>
<h1 id="15-template"><a href="#15-template" class="headerlink" title="15. template"></a>15. template</h1><ul>
<li>模板是 C++ 支持参数化多态的工具。为了能够编写与类型无关的代码。可分为以下两种：<ul>
<li>函数模板：针对仅函数参数不同的函数</li>
<li>类模板：针对仅数据成员和成员函数类型不同的类</li>
</ul>
</li>
<li>模板函数要定义在头文件中。因为在使用模板时，需要对模板参数进行确定。从而生成一个函数或是一个类。所以就需要模板的具体实现对于模板的使用者可见。所以需写到头文件中，在使用时包含。（也可以将实现写到使用的地方，但一般不这样做).</li>
<li>模板的声明或定义：只能在全局，命名空间，类范围 内。不能在局部范围，函数内进行。</li>
<li>语法<blockquote>
<p>T 为模板参数。在具体使用中，T 会被替换为不同的表达式 / 字符串。</p>
</blockquote>
</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>模板的形参：<ul>
<li>类型模板形参</li>
<li>非类型模板形参 （只可以为 int, *, &amp;. 而 double 之类的不行)</li>
<li>模板模板形参（以模板作为参数)</li>
</ul>
</li>
<li><p>默认形参：</p>
<ul>
<li><p>类型形参：可以为类模板的类型形参提供默认值，但不可对函数模板的类型形参提供。</p>
 <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T1</span>, <span class="title">class</span> <span class="title">T2</span>=<span class="title">int</span>&gt;<span class="title">class</span> <span class="title">A</span> &#123;</span></span><br><span class="line">   <span class="function">T1 <span class="title">func</span><span class="params">()</span></span>;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T1</span>, <span class="title">class</span> <span class="title">T2</span>&gt;    // 函数定义时不用写 <span class="title">T2</span> 的默认值（写上会有警告)</span></span><br><span class="line"><span class="class"><span class="title">T1</span> <span class="title">A</span>&lt;T1, T2&gt;:</span>:func() &#123;&#125;;</span><br></pre></td></tr></table></figure>
</li>
<li><p>非类型形参：可为类模板，函数模板的非类型形参提供默认值</p>
</li>
</ul>
</li>
<li><p>类型形参：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>, <span class="title">class</span> <span class="title">Y</span>&gt;.....（函数或类)   使用时：&lt;int, float&gt;....</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>非类型形参：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 可指定大小的栈：</span></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>, <span class="title">int</span> <span class="title">STACKSIZE</span>&gt;<span class="title">class</span> <span class="title">MyStack</span> &#123;</span></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">T <span class="built_in">stack</span>[STACKSIZE];</span><br><span class="line">...</span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 使用时：</span></span><br><span class="line">MyStack&lt;<span class="keyword">float</span>, <span class="number">100</span>&gt; a;     <span class="comment">//  a 为 float 类型，元素个数为 100 的栈</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="15-1-函数模板"><a href="#15-1-函数模板" class="headerlink" title="15.1. 函数模板"></a>15.1. 函数模板</h2><ul>
<li><p>格式：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> 形参名 1， <span class="title">class</span> 形参名 2...&gt; 返回类型 函数名（参数列表) &#123;</span>函数体&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<blockquote>
<p>template 和 class 为关键字。这里的 class 可使用 typename 代替。<br><code>&lt;&gt;</code>中的为模板形参。不能为空。一旦声明了模板形参，就可在函数内部使用该类型。</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">T</span> <span class="title">add</span>(<span class="title">T</span> <span class="title">a</span>, <span class="title">T</span> <span class="title">b</span>)</span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">        <span class="keyword">return</span> a+b;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 使用</span></span><br><span class="line"><span class="comment">// 此时，会因为 1 和 2 中 T 类型的不同，而生成两个不同的 add 函数。</span></span><br><span class="line"><span class="number">1.</span> add(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line"><span class="number">2.</span> add(<span class="number">1.3</span>, <span class="number">2.4</span>);</span><br><span class="line"><span class="number">3.</span> <span class="keyword">int</span> a= <span class="number">1</span>, b = <span class="number">2</span>;  add(a, b);</span><br></pre></td></tr></table></figure>
<h2 id="15-2-模板类"><a href="#15-2-模板类" class="headerlink" title="15.2. 模板类"></a>15.2. 模板类</h2><ul>
<li><p>在类的定义 / 该类的成员函数 前都需加</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>, ...&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>模板类的类名变为了：eg: <code>RN</code><br>要将之前使用类名的地方都替换为新类名</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;    // 要加模板声明</span></span><br><span class="line"><span class="class"><span class="title">class</span> <span class="title">RN</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">        RN(T _x = <span class="number">1</span>, T y = <span class="number">1</span>);</span><br><span class="line">        <span class="function">T <span class="title">func</span><span class="params">(T arg)</span></span>; <span class="comment">// 参数，返回值均为 T 类型</span></span><br><span class="line">        <span class="comment">// 参数，返回值均为该类 （但现在该类类名变为 RN&lt;T&gt;)</span></span><br><span class="line">        RN&lt;T&gt;&amp; operate=(RN&lt;T&gt; &amp;arg);</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">        T x, y;</span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;     // 要加模板声明</span></span><br><span class="line"><span class="class"><span class="title">RN</span>&lt;T&gt;:</span>:RN(T _x, T _y)</span><br><span class="line">&#123;</span><br><span class="line">            <span class="comment">//....</span></span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;    // 要加模板声明</span></span><br><span class="line"><span class="class"><span class="title">T</span> <span class="title">RN</span>&lt;T&gt;:</span>:func(T arg)</span><br><span class="line">&#123;</span><br><span class="line">            <span class="comment">//.........</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt;    // 要加模板声明</span></span><br><span class="line"><span class="class"><span class="title">RN</span>&lt;T&gt;&amp; <span class="title">RN</span>&lt;T&gt;:</span>:operate=(RN&lt;T&gt; &amp;rag)</span><br><span class="line">&#123;</span><br><span class="line">        <span class="comment">//</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 定义该类的对象时：</span></span><br><span class="line"> RN&lt;<span class="keyword">int</span>&gt; a;    <span class="comment">// 此时该对象对应的类 RN 中所有 T 都被 int 替代。</span></span><br><span class="line"><span class="comment">// 对于模板形参为多个的：</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">A</span>, <span class="title">class</span> <span class="title">B</span>&gt; <span class="title">class</span> <span class="title">My_RN</span> &#123;</span>...&#125;;</span><br><span class="line"><span class="comment">// 其定义对象时：My_RN &lt;int, float&gt; a;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="16-using"><a href="#16-using" class="headerlink" title="16. using"></a>16. using</h1><p>可用于以下情况：</p>
<ul>
<li>声明使用的命名空间</li>
<li>定义类型别名</li>
</ul>
<h2 id="16-1-声明使用的命名空间"><a href="#16-1-声明使用的命名空间" class="headerlink" title="16.1. 声明使用的命名空间"></a>16.1. 声明使用的命名空间</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> <span class="built_in">std</span>::<span class="built_in">cin</span>;   <span class="comment">// 使用 cin 就不需加 std:: 了</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;   <span class="comment">// 使用 std 命名空间</span></span><br></pre></td></tr></table></figure>
<ul>
<li>注意：头文件不应包含 using 声明 （防止引用该头文件的程序出现名字冲突)</li>
</ul>
<h2 id="16-2-定义类型别名"><a href="#16-2-定义类型别名" class="headerlink" title="16.2. 定义类型别名"></a>16.2. 定义类型别名</h2><p>C++11 规定了可使用 using 定义类型别名<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> MyInt = <span class="keyword">int</span>;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 等价于</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">int</span> MyInt;</span><br></pre></td></tr></table></figure></p>
<h1 id="17-virtual"><a href="#17-virtual" class="headerlink" title="17. virtual"></a>17. virtual</h1><p>虚函数</p>
<ul>
<li>纯虚函数：在虚函数声明加<code>=0</code></li>
</ul>
<h1 id="18-volatile"><a href="#18-volatile" class="headerlink" title="18. volatile"></a>18. volatile</h1><ul>
<li>表明本变量 / 类会被意想不到的地方改变。所以每次读取其时，都需要重新载入，而不是读取某寄存器中的存储值。</li>
<li>用于有多个执行序列的程序都要访问的变量上：<ul>
<li>多线程程序</li>
<li>中断中</li>
<li>并行设备的硬件寄存器</li>
</ul>
</li>
<li>问题：<ul>
<li>一个参数即可为 const, 又可能为 volatile 修饰。(eg: 只读的状态寄存器) const 表明只读属性。volatile 表明会被不确定因素修改。</li>
<li>一个指针也可为 volatile 修饰。在其他执行序列中修改了一个指针的指向时。（也就是该指针的值).</li>
</ul>
</li>
</ul>
<h1 id="19-enum-枚举类型"><a href="#19-enum-枚举类型" class="headerlink" title="19. enum 枚举类型"></a>19. enum 枚举类型</h1><ul>
<li>虽然枚举定义了唯一的类型，但实际 enum 是由某种整数类型表示的（成员大小).</li>
<li>c++11 标准中可以指定表示 enum 的类型。如果类型不够容纳所有枚举值，则会引发程序错误。</li>
<li>不指定类型时，默认情况是 int. 且编译器保证类型足够大，能容纳所有枚举值。</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">enum</span> Type : <span class="keyword">unsigned</span> <span class="keyword">long</span> <span class="keyword">long</span> &#123;</span><br><span class="line">    TypeIs_A = <span class="number">1</span></span><br><span class="line">    , TypeIs_B</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="19-1-枚举类型前置声明"><a href="#19-1-枚举类型前置声明" class="headerlink" title="19.1. 枚举类型前置声明"></a>19.1. 枚举类型前置声明</h2><ul>
<li>C++11 可提前声明 enum.</li>
<li>不限制作用域的 enum 需要制定成员大小。</li>
<li>限定作用域的 enum 可以不指定成员大小，隐式为 int.</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">enum</span> Type : <span class="keyword">unsigned</span> <span class="keyword">long</span> <span class="keyword">long</span>;    <span class="comment">// 必须指定成员大小</span></span><br><span class="line"><span class="keyword">enum</span> MyClass::Type; <span class="comment">// 限定作用域。可以不指定成员大小，默认为 int.</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>写在最后, 欢迎读者写下评论, 我们一起交流进步.</p>
</blockquote>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zhaoyongCNSX
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zhaoyongcnsx.github.io/2018/10/05/C++ 关键字整理/" title="C++ 关键字整理">https://zhaoyongcnsx.github.io/2018/10/05/C++ 关键字整理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/C/" rel="tag"># C++</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/05/Python 函数相关/" rel="next" title="Python 函数相关">
                <i class="fa fa-chevron-left"></i> Python 函数相关
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/myLogo.png"
                alt="zhaoyongCNSX" />
            
              <p class="site-author-name" itemprop="name">zhaoyongCNSX</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zhaoyongCNSX" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:zhaoyongCNSX@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://47.92.146.3" target="_blank" title="Self">
                      
                        <i class="fa fa-fw fa-globe"></i>Self</a>
                  </span>
                
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
              </a>
            </div>
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-auto"><span class="nav-text">1. auto</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-const"><span class="nav-text">2. const</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-修饰函数"><span class="nav-text">2.1. 修饰函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-修饰-指针-引用-类型的变量"><span class="nav-text">2.2. 修饰 指针 引用 类型的变量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-常对象成员"><span class="nav-text">2.3. 常对象成员</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-constexpr"><span class="nav-text">3. constexpr</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-constexpr变量"><span class="nav-text">3.1. constexpr变量</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-1-字面值类型"><span class="nav-text">3.1.1. 字面值类型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-constexpr和指针"><span class="nav-text">3.2. constexpr和指针</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-constexpr函数"><span class="nav-text">3.3. constexpr函数</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-decltype"><span class="nav-text">4. decltype</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-default"><span class="nav-text">5. default</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-delete"><span class="nav-text">6. delete</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7-explicit"><span class="nav-text">7. explicit</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#8-extern-链接指示"><span class="nav-text">8. extern 链接指示</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#9-friend"><span class="nav-text">9. friend</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#9-1-友元函数"><span class="nav-text">9.1. 友元函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-2-友元类"><span class="nav-text">9.2. 友元类</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#10-inline"><span class="nav-text">10. inline</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#11-mutable"><span class="nav-text">11. mutable</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#12-new"><span class="nav-text">12. new</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#13-operator"><span class="nav-text">13. operator</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#14-static"><span class="nav-text">14. static</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#14-1-示例"><span class="nav-text">14.1. 示例</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#15-template"><span class="nav-text">15. template</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#15-1-函数模板"><span class="nav-text">15.1. 函数模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#15-2-模板类"><span class="nav-text">15.2. 模板类</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#16-using"><span class="nav-text">16. using</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#16-1-声明使用的命名空间"><span class="nav-text">16.1. 声明使用的命名空间</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#16-2-定义类型别名"><span class="nav-text">16.2. 定义类型别名</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#17-virtual"><span class="nav-text">17. virtual</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#18-volatile"><span class="nav-text">18. volatile</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#19-enum-枚举类型"><span class="nav-text">19. enum 枚举类型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#19-1-枚举类型前置声明"><span class="nav-text">19.1. 枚举类型前置声明</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaoyongCNSX</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">7.6k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  








  
  





  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/canvas_sphere.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'zhaoyongCNSX@163.com',
            repo: 'blogs',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: 'b00a50e88366c64af5b8772b1206047aa7b3ec3b',
            
                client_id: 'cc6ed49c5b86432240d3'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("TDDsUDe2bNJ9AuDLtdMqfUNo-gzGzoHsz", "0RHypA7igWU0QbMnfRg9D6DU");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
